package com.ben.chatroom.service;

import com.ben.chatroom.common.codec.ProtobufDecoder;
import com.ben.chatroom.common.codec.ProtobufEncoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.concurrent.GenericFutureListener;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * @author huangyijun
 */
@Slf4j
@Service
public class NettyClient {

  @Getter
  @Setter
  private String host;

  @Getter
  @Setter
  private int port;


  private Bootstrap bootstrap;
  private final EventLoopGroup group;

  @Setter
  private GenericFutureListener<ChannelFuture> connectedListener;

  public NettyClient() {
    this.group = new NioEventLoopGroup();
  }


  public void close() {
    group.shutdownGracefully();
  }

  /**
   * 重连
   */
  public void doConnect() {
    bootstrap = new Bootstrap();

    bootstrap
      .group(group)
      .channel(NioSocketChannel.class)
      .option(ChannelOption.SO_KEEPALIVE, true)
      .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
      .remoteAddress(host, port);

    bootstrap.handler(new ChannelInitializer<SocketChannel>() {
      @Override
      protected void initChannel(SocketChannel socketChannel) throws Exception {
        ChannelPipeline pipeline = socketChannel.pipeline();
        pipeline.addLast("decoder", new ProtobufDecoder());
        pipeline.addLast("encoder", new ProtobufEncoder());


      }
    });

    ChannelFuture future = bootstrap.connect();
    future.addListener(connectedListener);

  }

}
